@andy.ian/dsh-homing 2.1.12 → 2.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -32,6 +32,7 @@ import { createRestartPolicy } from './restart/face.mjs';
32
32
  import { renderTermPage } from './lib/term-page.mjs';
33
33
  import * as compress from './lib/compress.mjs';
34
34
  import * as office from './lib/office.mjs';
35
+ import * as markdown from './lib/markdown.mjs';
35
36
  import * as windowRemote from './lib/window-remote.mjs';
36
37
  import { setOrientation, ensureLandscape } from './lib/orientation.mjs';
37
38
  import { protectSecret, unprotectSecret } from './lib/secret.mjs';
@@ -2869,7 +2870,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2869
2870
  return;
2870
2871
  }
2871
2872
 
2872
- if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/pdf' || url.pathname === '/files/download' || url.pathname === '/files/compress' || url.pathname === '/files/run'
2873
+ if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/pdf' || url.pathname === '/files/download' || url.pathname === '/files/raw' || url.pathname === '/files/compress' || url.pathname === '/files/run'
2873
2874
  || url.pathname === '/files/rename'
2874
2875
  || url.pathname === '/files/delete' || url.pathname === '/files/paste'
2875
2876
  || url.pathname === '/files/mkdir' || url.pathname === '/files/newfile') {
@@ -2978,6 +2979,42 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2978
2979
  return;
2979
2980
  }
2980
2981
 
2982
+ // Markdown 图片:只允许常见图片格式,内联返回(不下载)
2983
+ if (url.pathname === '/files/raw' && req.method === 'GET') {
2984
+ const target = filebrowse.resolvePath(url.searchParams.get('path') ?? '');
2985
+ const typeByExt = {
2986
+ '.png': 'image/png',
2987
+ '.jpg': 'image/jpeg',
2988
+ '.jpeg': 'image/jpeg',
2989
+ '.gif': 'image/gif',
2990
+ '.webp': 'image/webp',
2991
+ '.bmp': 'image/bmp',
2992
+ };
2993
+ const ext = path.extname(target).toLowerCase();
2994
+ const contentType = typeByExt[ext];
2995
+ if (contentType === undefined) {
2996
+ res.writeHead(415, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
2997
+ res.end('不支持的图片格式\n');
2998
+ return;
2999
+ }
3000
+ let stat = null;
3001
+ try { stat = fs.statSync(target); } catch { stat = null; }
3002
+ if (!stat || !stat.isFile() || stat.size > 20 * 1024 * 1024) {
3003
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
3004
+ res.end('图片不存在或过大\n');
3005
+ return;
3006
+ }
3007
+ appendAudit(dir, 'file-image', { path: target, bytes: stat.size });
3008
+ res.writeHead(200, {
3009
+ 'content-type': contentType,
3010
+ 'content-length': String(stat.size),
3011
+ 'cache-control': 'no-store',
3012
+ 'x-content-type-options': 'nosniff',
3013
+ });
3014
+ fs.createReadStream(target).pipe(res);
3015
+ return;
3016
+ }
3017
+
2981
3018
  // PDF / Office 在线预览:PDF 直接流式返回;Office 先转 PDF(带缓存)
2982
3019
  if (url.pathname === '/files/pdf' && req.method === 'GET') {
2983
3020
  const target = filebrowse.resolvePath(url.searchParams.get('path') ?? '');
@@ -3041,6 +3078,21 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3041
3078
  return;
3042
3079
  }
3043
3080
  const info = filebrowse.readTextFile(asked);
3081
+ const raw = url.searchParams.get('raw') === '1';
3082
+ if (!raw && info.text !== undefined && markdown.isMarkdownFile(info.path)) {
3083
+ // Markdown:服务端渲染成安全 HTML;相对图片走 /files/raw,相对文件链接走文件页
3084
+ const baseDir = path.dirname(info.path);
3085
+ const rendered = markdown.renderMarkdown(info.text, {
3086
+ resolvePath: (relative) => path.resolve(baseDir, relative),
3087
+ imageHref: (absPath) => '/files/raw?path=' + encodeURIComponent(absPath),
3088
+ fileHref: (absPath) => (markdown.isMarkdownFile(absPath)
3089
+ ? '/files/view?path=' + encodeURIComponent(absPath)
3090
+ : '/files/download?path=' + encodeURIComponent(absPath)),
3091
+ });
3092
+ appendAudit(dir, 'file-view', { path: info.path, kind: 'markdown' });
3093
+ sendHtml(renderFileView({ info, rendered }));
3094
+ return;
3095
+ }
3044
3096
  appendAudit(dir, 'file-view', { path: info.path });
3045
3097
  sendHtml(renderFileView({ info }));
3046
3098
  return;
@@ -37,6 +37,30 @@ const STYLE = `
37
37
  .chip { background:#1b2030; border:1px solid #2a3550; color:#9fc0ff; border-radius:999px; padding:6px 12px; font-size:12px; }
38
38
  .crumb { color:#8ab4f8; }
39
39
  .kbd { font-family: ui-monospace, Menlo, Consolas, monospace; background:#1d2229; padding:1px 5px; border-radius:4px; font-size:12px; }
40
+ .md-body { font-size:14px; line-height:1.7; color:#dfe6ef; word-break:break-word; }
41
+ .md-body > :first-child { margin-top:0; }
42
+ .md-body h1, .md-body h2, .md-body h3, .md-body h4, .md-body h5, .md-body h6 { line-height:1.35; margin:20px 0 10px; color:#f2f5f9; }
43
+ .md-body h1 { font-size:22px; border-bottom:1px solid #262b35; padding-bottom:8px; }
44
+ .md-body h2 { font-size:19px; border-bottom:1px solid #1d222b; padding-bottom:6px; }
45
+ .md-body h3 { font-size:17px; }
46
+ .md-body h4 { font-size:15px; }
47
+ .md-body p { margin:10px 0; }
48
+ .md-body ul, .md-body ol { padding-left:22px; margin:10px 0; }
49
+ .md-body li { margin:4px 0; }
50
+ .md-body li > ul, .md-body li > ol { margin:4px 0; }
51
+ .md-body code { font-family: ui-monospace, Menlo, Consolas, monospace; background:#1b2028; border:1px solid #262d38; border-radius:5px; padding:1px 5px; font-size:12.5px; }
52
+ .md-body pre { background:#12151b; border:1px solid #21262f; border-radius:10px; padding:12px; overflow:auto; margin:12px 0; }
53
+ .md-body pre code { background:none; border:0; padding:0; font-size:12.5px; }
54
+ .md-body blockquote { margin:12px 0; padding:8px 12px; border-left:3px solid #3f5f9c; background:#151a22; color:#b9c3d1; border-radius:0 8px 8px 0; }
55
+ .md-body blockquote p { margin:4px 0; }
56
+ .md-body table { width:100%; border-collapse:collapse; margin:12px 0; font-size:13px; }
57
+ .md-body th, .md-body td { padding:8px 10px; border:1px solid #262d38; text-align:left; vertical-align:top; }
58
+ .md-body th { background:#1b2028; color:#cfd8e3; }
59
+ .md-body hr { border:0; border-top:1px solid #262b35; margin:18px 0; }
60
+ .md-body img { max-width:100%; height:auto; border-radius:8px; }
61
+ .md-body a { color:#8ab4f8; text-decoration:none; border-bottom:1px solid rgba(138,180,248,.35); }
62
+ .md-body input[type=checkbox] { margin:0 4px 0 0; vertical-align:middle; }
63
+ .md-body a.md-img { border-bottom:0; }
40
64
  `
41
65
 
42
66
  export function layout({ title, body }) {
@@ -401,16 +425,25 @@ export function renderCompressPage({ target, archive, message, isError, done = f
401
425
  return layout({ title: '加密压缩 · ' + name, body })
402
426
  }
403
427
 
404
- /** 文件内容页 *//** 文件内容页 */
405
- export function renderFile({ info, message, isError }) {
428
+ /** 文件内容页(text=源码;rendered=Markdown 渲染结果) */
429
+ export function renderFile({ info, message, isError, rendered = null }) {
430
+ const isMarkdown = /\.(?:md|markdown|mdown|mkd)$/iu.test(info.path)
431
+ const sourceHref = '/files/view?path=' + encodeURIComponent(info.path) + '&raw=1'
432
+ const renderedHref = '/files/view?path=' + encodeURIComponent(info.path)
433
+ const toggle = rendered
434
+ ? `<div class="chips"><a class="chip" href="${sourceHref}">查看源码</a></div>`
435
+ : (isMarkdown && info.error === undefined
436
+ ? `<div class="chips"><a class="chip" href="${renderedHref}">渲染 Markdown</a></div>`
437
+ : '')
406
438
  const body = `
407
439
  <div class="bar">
408
440
  <h1>${escapeHtml(info.path.split(/[\\/]/u).pop() ?? info.path)}</h1>
409
441
  <div class="path">${escapeHtml(info.path)}</div>
442
+ ${toggle}
410
443
  </div>
411
444
  ${messageHtml(message, isError)}
412
445
  ${info.error ? `<div class="msg err">${escapeHtml(info.error)}</div>` : ''}
413
- ${info.text !== undefined ? `<pre>${escapeHtml(info.text)}</pre>` : ''}
446
+ ${rendered ? `<article class="md-body">${rendered.html}</article>` : (info.text !== undefined ? `<pre>${escapeHtml(info.text)}</pre>` : '')}
414
447
  <div class="row">
415
448
  <a class="btn ghost" href="/files?path=${encodeURIComponent(info.path.replace(/[\\/][^\\/]*$/u, '') || '/')}"
416
449
  style="flex:1;text-align:center;padding:10px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;font-size:14px">返回目录</a>
@@ -0,0 +1,384 @@
1
+ /**
2
+ * 轻量 Markdown 渲染器(零依赖、服务端渲染)。
3
+ *
4
+ * 目标:在手机 DSH 文件页里直接阅读 .md 文档。
5
+ *
6
+ * 安全原则:
7
+ * - 原始 HTML 一律转义,不直接输出(防止 markdown 文件注入脚本)
8
+ * - 链接/图片 URL 只允许 http(s)、mailto、tel、锚点、站内相对路径
9
+ * - javascript:/data:/vbscript:/file: 等协议直接拒绝
10
+ *
11
+ * 支持:标题、段落、列表(含嵌套/任务列表)、引用、代码块、行内代码、
12
+ * 粗体/斜体/删除线、链接、图片、表格、分隔线、自动链接。
13
+ */
14
+
15
+ const ESCAPE_MAP = {
16
+ '&': '&amp;',
17
+ '<': '&lt;',
18
+ '>': '&gt;',
19
+ '"': '&quot;',
20
+ "'": '&#39;',
21
+ }
22
+
23
+ export function escapeHtml(value) {
24
+ return String(value ?? '').replace(/[&<>"']/gu, (char) => ESCAPE_MAP[char])
25
+ }
26
+
27
+ const DANGEROUS_PROTOCOL = /^\s*(?:javascript|data|vbscript|file|blob)\s*:/iu
28
+
29
+ function cleanUrl(raw) {
30
+ let url = String(raw ?? '').trim()
31
+ if (url.startsWith('<') && url.endsWith('>')) url = url.slice(1, -1).trim()
32
+ if (url === '') return null
33
+ if (DANGEROUS_PROTOCOL.test(url)) return null
34
+ return url
35
+ }
36
+
37
+ function isExternal(url) {
38
+ return /^[a-z][a-z0-9+.-]*:/iu.test(url)
39
+ }
40
+
41
+ function splitUrl(url) {
42
+ const hashIndex = url.indexOf('#')
43
+ const hash = hashIndex >= 0 ? url.slice(hashIndex) : ''
44
+ let pathPart = hashIndex >= 0 ? url.slice(0, hashIndex) : url
45
+ const queryIndex = pathPart.indexOf('?')
46
+ const query = queryIndex >= 0 ? pathPart.slice(queryIndex) : ''
47
+ if (queryIndex >= 0) pathPart = pathPart.slice(0, queryIndex)
48
+ return { path: pathPart, query, hash }
49
+ }
50
+
51
+ /**
52
+ * 解析站内相对路径(图片/文件链接)。
53
+ * @returns {{kind:'external',url:string}|{kind:'file',path:string}|null}
54
+ */
55
+ function resolveTarget(raw, options) {
56
+ const url = cleanUrl(raw)
57
+ if (url === null) return null
58
+ if (url.startsWith('#')) return { kind: 'anchor', url }
59
+ if (isExternal(url)) {
60
+ if (/^https?:/iu.test(url)) return { kind: 'external', url }
61
+ if (/^(?:mailto|tel):/iu.test(url)) return { kind: 'external', url }
62
+ return null
63
+ }
64
+ const { path: pathPart, query, hash } = splitUrl(url)
65
+ if (pathPart === '') return { kind: 'anchor', url: '#' + hash.replace(/^#/u, '') }
66
+ let decoded = pathPart
67
+ try { decoded = decodeURIComponent(pathPart) } catch { /* 保持原样 */ }
68
+ if (decoded.includes('\0')) return null
69
+ const resolved = options.resolvePath ? options.resolvePath(decoded) : decoded
70
+ if (!resolved) return null
71
+ const suffix = query + hash
72
+ return { kind: 'file', path: resolved, suffix }
73
+ }
74
+
75
+ function inline(text, options) {
76
+ const stash = []
77
+ const put = (html) => {
78
+ const token = '\u0000' + stash.length + '\u0000'
79
+ stash.push(html)
80
+ return token
81
+ }
82
+
83
+ let out = String(text ?? '')
84
+
85
+ // 1) 行内代码 `code`
86
+ out = out.replace(/(`+)([^`]+?)\1/gu, (match, ticks, code) => put('<code>' + escapeHtml(code.trim()) + '</code>'))
87
+
88
+ // 2) 自动链接 <https://...>
89
+ out = out.replace(/<((?:https?|mailto):[^<>\s]+)>/giu, (match, url) => {
90
+ const target = resolveTarget(url, options)
91
+ if (target === null) return escapeHtml(match)
92
+ return put('<a href="' + escapeHtml(url) + '" target="_blank" rel="noopener noreferrer">' + escapeHtml(url) + '</a>')
93
+ })
94
+
95
+ // 3) 图片 ![alt](url "title")
96
+ out = out.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/gu, (match, alt, url) => {
97
+ const target = resolveTarget(url, options)
98
+ if (target === null) return escapeHtml(match)
99
+ const altText = escapeHtml(alt || '图片')
100
+ if (target.kind === 'external') {
101
+ // CSP 只允许站内图片:外链图片降级为链接,避免破图
102
+ return put('<a href="' + escapeHtml(target.url) + '" target="_blank" rel="noopener noreferrer">' + altText + '</a>')
103
+ }
104
+ if (target.kind !== 'file') return escapeHtml(match)
105
+ const src = options.imageHref ? options.imageHref(target.path) : target.path
106
+ if (!src) return escapeHtml(match)
107
+ return put('<a class="md-img" href="' + escapeHtml(src) + '" target="_blank" rel="noopener noreferrer"><img src="' + escapeHtml(src) + '" alt="' + altText + '" loading="lazy"></a>')
108
+ })
109
+
110
+ // 4) 链接 [text](url "title")
111
+ out = out.replace(/\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/gu, (match, label, url) => {
112
+ const target = resolveTarget(url, options)
113
+ if (target === null) return escapeHtml(match)
114
+ const text = inlineInline(label, options)
115
+ if (target.kind === 'anchor') {
116
+ return put('<a href="' + escapeHtml(target.url) + '">' + text + '</a>')
117
+ }
118
+ if (target.kind === 'external') {
119
+ return put('<a href="' + escapeHtml(target.url) + '" target="_blank" rel="noopener noreferrer">' + text + '</a>')
120
+ }
121
+ const href = options.fileHref ? options.fileHref(target.path, target.suffix) : target.path + target.suffix
122
+ if (!href) return escapeHtml(match)
123
+ return put('<a href="' + escapeHtml(href) + '">' + text + '</a>')
124
+ })
125
+
126
+ // 5) 转义剩余 HTML
127
+ out = escapeHtml(out)
128
+
129
+ // 6) 反斜杠转义:先占位成字面字符,避免后续强调语法误伤
130
+ out = out.replace(/\\([\\`*_{}\[\]()#+\-.!|>~])/gu, (match, char) => put(escapeHtml(char)))
131
+
132
+ // 7) 粗体 / 斜体 / 删除线
133
+ out = out.replace(/\*\*([^*]+)\*\*/gu, '<strong>$1</strong>')
134
+ out = out.replace(/__([^_]+)__/gu, '<strong>$1</strong>')
135
+ out = out.replace(/(^|[^*])\*([^*\s][^*]*?)\*/gu, '$1<em>$2</em>')
136
+ out = out.replace(/(^|[^_])_([^_\s][^_]*?)_(?!_)/gu, '$1<em>$2</em>')
137
+ out = out.replace(/~~([^~]+)~~/gu, '<del>$1</del>')
138
+
139
+ // 8) 恢复占位符
140
+ out = out.replace(/\u0000(\d+)\u0000/gu, (match, index) => stash[Number(index)] ?? '')
141
+ return out
142
+ }
143
+
144
+ function inlineInline(text, options) {
145
+ return inline(text, options)
146
+ }
147
+
148
+ function isBlank(line) {
149
+ return /^\s*$/u.test(line)
150
+ }
151
+
152
+ function matchFence(line) {
153
+ const match = /^\s{0,3}(`{3,}|~{3,})\s*([\w+-]*)\s*$/u.exec(line)
154
+ return match ? { marker: match[1][0], length: match[1].length, lang: match[2] || '' } : null
155
+ }
156
+
157
+ function matchHeading(line) {
158
+ const match = /^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$/u.exec(line)
159
+ return match ? { level: match[1].length, text: match[2] } : null
160
+ }
161
+
162
+ function matchHr(line) {
163
+ return /^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/u.test(line)
164
+ }
165
+
166
+ function matchQuote(line) {
167
+ return /^\s{0,3}>\s?(.*)$/u.exec(line)
168
+ }
169
+
170
+ function matchListItem(line) {
171
+ const unordered = /^(\s*)([-*+])\s+(.*)$/u.exec(line)
172
+ if (unordered) return { indent: unordered[1].replace(/\t/gu, ' ').length, ordered: false, text: unordered[3] }
173
+ const ordered = /^(\s*)(\d{1,9})[.)]\s+(.*)$/u.exec(line)
174
+ if (ordered) return { indent: ordered[1].replace(/\t/gu, ' ').length, ordered: true, text: ordered[3] }
175
+ return null
176
+ }
177
+
178
+ function isTableSeparator(line) {
179
+ return /^\s*\|?\s*:?-{2,}:?\s*(?:\|\s*:?-{2,}:?\s*)+\|?\s*$/u.test(line)
180
+ }
181
+
182
+ function splitTableRow(line) {
183
+ let text = line.trim()
184
+ if (text.startsWith('|')) text = text.slice(1)
185
+ if (text.endsWith('|')) text = text.slice(0, -1)
186
+ return text.split('|').map((cell) => cell.trim().replace(/\\\|/gu, '|'))
187
+ }
188
+
189
+ function renderList(lines, start, options) {
190
+ const first = matchListItem(lines[start])
191
+ const baseIndent = first.indent
192
+ const baseOrdered = first.ordered
193
+ const items = []
194
+ let i = start
195
+
196
+ while (i < lines.length) {
197
+ const item = matchListItem(lines[i])
198
+ if (item === null) break
199
+ if (item.indent < baseIndent) break
200
+ if (item.ordered !== baseOrdered) break
201
+ if (item.indent > baseIndent) break // 同级里出现更深缩进:交给上一层的子列表处理
202
+
203
+ let text = item.text
204
+ let nested = ''
205
+ let j = i + 1
206
+ while (j < lines.length) {
207
+ if (isBlank(lines[j])) {
208
+ let k = j + 1
209
+ while (k < lines.length && isBlank(lines[k])) k += 1
210
+ if (k >= lines.length) { j = k; break }
211
+ const after = matchListItem(lines[k])
212
+ if (after === null) { j = k; break }
213
+ if (after.indent > item.indent + 1) {
214
+ const sub = renderList(lines, k, options)
215
+ nested += sub.html
216
+ j = sub.next
217
+ continue
218
+ }
219
+ if (after.indent <= item.indent) break
220
+ j = k
221
+ continue
222
+ }
223
+ const next = matchListItem(lines[j])
224
+ if (next !== null) {
225
+ if (next.indent > item.indent + 1) {
226
+ const sub = renderList(lines, j, options)
227
+ nested += sub.html
228
+ j = sub.next
229
+ continue
230
+ }
231
+ if (next.indent <= item.indent) break
232
+ // 同层新项
233
+ break
234
+ }
235
+ if (/^\s{2,}\S/u.test(lines[j])) {
236
+ text += '\n' + lines[j].trim()
237
+ j += 1
238
+ continue
239
+ }
240
+ break
241
+ }
242
+ items.push({ text, nested })
243
+ i = j
244
+ }
245
+
246
+ const tag = baseOrdered ? 'ol' : 'ul'
247
+ const html = items.map((item) => {
248
+ let content = item.text
249
+ let checkbox = ''
250
+ const task = /^\[([ xX])\]\s+(.*)$/u.exec(content)
251
+ if (task !== null) {
252
+ checkbox = '<input type="checkbox" disabled' + (task[1].toLowerCase() === 'x' ? ' checked' : '') + '> '
253
+ content = task[2]
254
+ }
255
+ return '<li>' + checkbox + inline(content, options) + item.nested + '</li>'
256
+ }).join('')
257
+ return { html: '<' + tag + '>' + html + '</' + tag + '>', next: i }
258
+ }
259
+
260
+ function renderTable(lines, start, options) {
261
+ const header = splitTableRow(lines[start])
262
+ const rows = []
263
+ let i = start + 2
264
+ while (i < lines.length && /\|/u.test(lines[i]) && !isBlank(lines[i])) {
265
+ rows.push(splitTableRow(lines[i]))
266
+ i += 1
267
+ }
268
+ const head = header.map((cell) => '<th>' + inline(cell, options) + '</th>').join('')
269
+ const body = rows.map((row) => {
270
+ const cells = header.map((_, index) => '<td>' + inline(row[index] ?? '', options) + '</td>').join('')
271
+ return '<tr>' + cells + '</tr>'
272
+ }).join('')
273
+ return { html: '<table><thead><tr>' + head + '</tr></thead><tbody>' + body + '</tbody></table>', next: i }
274
+ }
275
+
276
+ function startsBlock(line) {
277
+ return matchFence(line) !== null
278
+ || matchHeading(line) !== null
279
+ || matchHr(line)
280
+ || matchQuote(line) !== null
281
+ || matchListItem(line) !== null
282
+ || /^\s{0,3}(?:`{3,}|~{3,})/u.test(line)
283
+ }
284
+
285
+ /**
286
+ * 渲染 Markdown。
287
+ *
288
+ * @param {string} text
289
+ * @param {object} [options]
290
+ * @param {(relativePath: string) => string|null} [options.resolvePath] 相对路径 → 绝对路径
291
+ * @param {(absPath: string) => string|null} [options.imageHref] 图片 → 站内 URL
292
+ * @param {(absPath: string, suffix?: string) => string|null} [options.fileHref] 文件链接 → 站内 URL
293
+ * @returns {{html: string}}
294
+ */
295
+ export function renderMarkdown(text, options = {}) {
296
+ const lines = String(text ?? '').replace(/\r\n?/gu, '\n').split('\n')
297
+ const out = []
298
+ let i = 0
299
+
300
+ while (i < lines.length) {
301
+ const line = lines[i]
302
+ if (isBlank(line)) { i += 1; continue }
303
+
304
+ // 代码块
305
+ const fence = matchFence(line)
306
+ if (fence !== null) {
307
+ i += 1
308
+ const code = []
309
+ while (i < lines.length) {
310
+ const closing = matchFence(lines[i])
311
+ if (closing !== null && closing.marker === fence.marker && closing.length >= fence.length) { i += 1; break }
312
+ code.push(lines[i])
313
+ i += 1
314
+ }
315
+ const langClass = fence.lang ? ' class="language-' + escapeHtml(fence.lang) + '"' : ''
316
+ out.push('<pre><code' + langClass + '>' + escapeHtml(code.join('\n')) + '</code></pre>')
317
+ continue
318
+ }
319
+
320
+ // 标题
321
+ const heading = matchHeading(line)
322
+ if (heading !== null) {
323
+ const tag = 'h' + Math.min(6, Math.max(1, heading.level))
324
+ out.push('<' + tag + '>' + inline(heading.text, options) + '</' + tag + '>')
325
+ i += 1
326
+ continue
327
+ }
328
+
329
+ // 分隔线
330
+ if (matchHr(line)) { out.push('<hr>'); i += 1; continue }
331
+
332
+ // 引用(递归渲染内容)
333
+ const quote = matchQuote(line)
334
+ if (quote !== null) {
335
+ const quoted = []
336
+ while (i < lines.length) {
337
+ const current = matchQuote(lines[i])
338
+ if (current === null) break
339
+ quoted.push(current[1])
340
+ i += 1
341
+ }
342
+ out.push('<blockquote>' + renderMarkdown(quoted.join('\n'), options).html + '</blockquote>')
343
+ continue
344
+ }
345
+
346
+ // 表格
347
+ if (/\|/u.test(line) && i + 1 < lines.length && isTableSeparator(lines[i + 1])) {
348
+ const table = renderTable(lines, i, options)
349
+ out.push(table.html)
350
+ i = table.next
351
+ continue
352
+ }
353
+
354
+ // 列表
355
+ if (matchListItem(line) !== null) {
356
+ const list = renderList(lines, i, options)
357
+ out.push(list.html)
358
+ i = list.next
359
+ continue
360
+ }
361
+
362
+ // 段落:连续非空行(遇到其他块级语法停止)
363
+ const paragraph = [line]
364
+ i += 1
365
+ while (i < lines.length && !isBlank(lines[i])) {
366
+ const current = lines[i]
367
+ if (i + 1 < lines.length && isTableSeparator(lines[i + 1])) break
368
+ if (startsBlock(current) && paragraph.length > 0 && !/^\s{2,}/u.test(current)) break
369
+ paragraph.push(current)
370
+ i += 1
371
+ }
372
+ let html = inline(paragraph.join('\n'), options)
373
+ // 段内换行:行尾两个空格 / 反斜杠 → <br>
374
+ html = html.replace(/ {2,}\n/gu, '<br>\n').replace(/\\\n/gu, '<br>\n').replace(/\n/gu, ' ')
375
+ out.push('<p>' + html.trim() + '</p>')
376
+ }
377
+
378
+ return { html: out.join('\n') }
379
+ }
380
+
381
+ /** 是否看起来像 Markdown 文档(按扩展名判断) */
382
+ export function isMarkdownFile(filePath) {
383
+ return /\.(?:md|markdown|mdown|mkd|mdx?)$/iu.test(String(filePath ?? ''))
384
+ }
@@ -14519,6 +14519,9 @@ function showPicker(windows, kind) {
14519
14519
  }
14520
14520
  async function rotateDesktop(mode) {
14521
14521
  setStatus(mode === "portrait" ? "\u6B63\u5728\u5207\u7AD6\u5C4F\u2026" : "\u6B63\u5728\u5207\u6A2A\u5C4F\u2026");
14522
+ userClosed = true;
14523
+ if (rfb !== null) cleanup();
14524
+ await new Promise((resolve) => setTimeout(resolve, 350));
14522
14525
  try {
14523
14526
  const response = await fetch("/remote/input", {
14524
14527
  method: "POST",
@@ -14528,14 +14531,22 @@ async function rotateDesktop(mode) {
14528
14531
  const data = await response.json();
14529
14532
  if (!data.ok) {
14530
14533
  setStatus("\u5207\u6362\u5931\u8D25\uFF1A" + (data.detail || "\u672A\u77E5\u539F\u56E0"), "bad");
14534
+ userClosed = false;
14535
+ connect();
14531
14536
  return;
14532
14537
  }
14533
- setStatus(mode === "portrait" ? "\u5DF2\u5207\u7AD6\u5C4F\uFF0C\u753B\u9762\u81EA\u52A8\u9002\u914D\u4E2D\u2026" : "\u5DF2\u5207\u6A2A\u5C4F\uFF0C\u753B\u9762\u81EA\u52A8\u9002\u914D\u4E2D\u2026", "ok");
14538
+ setStatus(mode === "portrait" ? "\u5DF2\u5207\u7AD6\u5C4F\uFF0C\u6B63\u5728\u91CD\u8FDE\u2026" : "\u5DF2\u5207\u6A2A\u5C4F\uFF0C\u6B63\u5728\u91CD\u8FDE\u2026", "ok");
14534
14539
  lastFbSize = "";
14535
- setTimeout(refreshFramebufferView, 1200);
14536
- setTimeout(refreshFramebufferView, 3e3);
14540
+ setTimeout(() => {
14541
+ userClosed = false;
14542
+ connect();
14543
+ setTimeout(refreshFramebufferView, 1500);
14544
+ setTimeout(refreshFramebufferView, 3500);
14545
+ }, 900);
14537
14546
  } catch (error) {
14538
14547
  setStatus("\u5207\u6362\u5931\u8D25\uFF1A" + (error?.message ?? error), "bad");
14548
+ userClosed = false;
14549
+ connect();
14539
14550
  }
14540
14551
  }
14541
14552
  var keyboardInput = null;
package/lib/vnc-app.js CHANGED
@@ -412,10 +412,20 @@ function showPicker(windows, kind) {
412
412
  document.body.append(mask)
413
413
  }
414
414
 
415
- /** 切换电脑屏幕方向;旋转后帧缓冲尺寸变化,重连一次以适配 */
415
+ /**
416
+ * 切换电脑屏幕方向。
417
+ *
418
+ * TightVNC 在"有客户端连接"时旋转屏幕会出现帧缓冲不同步(任务栏/壁纸不刷新、
419
+ * 尺寸还是旧的),所以流程是:断开 VNC → 转屏 → 重连,让服务器按新尺寸初始化。
420
+ */
416
421
  async function rotateDesktop(mode) {
417
422
  setStatus(mode === 'portrait' ? '正在切竖屏…' : '正在切横屏…')
423
+ // 1) 先断开当前 VNC 连接(userClosed 防止自动重连插进来)
424
+ userClosed = true
425
+ if (rfb !== null) cleanup()
426
+ await new Promise((resolve) => setTimeout(resolve, 350))
418
427
  try {
428
+ // 2) 转屏
419
429
  const response = await fetch('/remote/input', {
420
430
  method: 'POST',
421
431
  headers: { 'content-type': 'application/json' },
@@ -424,16 +434,23 @@ async function rotateDesktop(mode) {
424
434
  const data = await response.json()
425
435
  if (!data.ok) {
426
436
  setStatus('切换失败:' + (data.detail || '未知原因'), 'bad')
437
+ userClosed = false
438
+ connect()
427
439
  return
428
440
  }
429
- // 不再强制重连:noVNC 会随帧缓冲尺寸变化自动适配;
430
- // 若 TightVNC 因分辨率变化断开,由下面的自动重连逻辑接管。
431
- setStatus(mode === 'portrait' ? '已切竖屏,画面自动适配中…' : '已切横屏,画面自动适配中…', 'ok')
432
- lastFbSize = '' // 强制下一轮重新计算缩放
433
- setTimeout(refreshFramebufferView, 1200)
434
- setTimeout(refreshFramebufferView, 3000)
441
+ // 3) 等显示模式稳定后重连(新连接会拿到新的帧缓冲尺寸)
442
+ setStatus(mode === 'portrait' ? '已切竖屏,正在重连…' : '已切横屏,正在重连…', 'ok')
443
+ lastFbSize = ''
444
+ setTimeout(() => {
445
+ userClosed = false
446
+ connect()
447
+ setTimeout(refreshFramebufferView, 1500)
448
+ setTimeout(refreshFramebufferView, 3500)
449
+ }, 900)
435
450
  } catch (error) {
436
451
  setStatus('切换失败:' + (error?.message ?? error), 'bad')
452
+ userClosed = false
453
+ connect()
437
454
  }
438
455
  }
439
456
 
package/lib/vnc-boot.js CHANGED
@@ -32,7 +32,7 @@
32
32
 
33
33
  const script = document.createElement('script')
34
34
  script.type = 'module'
35
- script.src = '/vnc/bundle.js?v=45'
35
+ script.src = '/vnc/bundle.js?v=46'
36
36
  script.onload = () => {
37
37
  boot('就绪,点连接')
38
38
  report('bundle-loaded', 'ok')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andy.ian/dsh-homing",
3
- "version": "2.1.12",
3
+ "version": "2.1.14",
4
4
  "type": "module",
5
5
  "description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
6
6
  "keywords": [